package com.handong.handserialprogram.widget;

import android.content.Context;
import android.os.Build;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handong.handserialprogram.R;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SystemUtil;

import java.lang.reflect.Field;


/**
 * Created by userKey on 2017/4/1.
 */

public class IPInputView extends LinearLayout {

    public static final String TAG = "IPInputView";
    private Context mContext;

    private EditText[] mEditViewArray;

    private static final int DEFAULT_NUMBER = 0;
    private static final String DEFAULT_TYPE = "number";

    public IPInputView(Context context) {
        super(context);
        initView();
    }

    public IPInputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    private void initView() {
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);
        setBackgroundResource(R.drawable.line_back_circle);

        mEditViewArray = new EditText[4];
        float dpi = SystemUtil.displayMetricsDpi(getContext());
        int padding = Math.round(7 * dpi);
        int width = Math.round(68 * dpi);
        for (int i = 0; i < mEditViewArray.length; i++) {
            mEditViewArray[i] = getEditText(width, padding);
            addView(mEditViewArray[i]);
            if (i != 3) {
                addView(getBlackPoint());
            }
        }

        initListener();
    }

    private EditText getEditText(int width, int padding) {

        EditText editText = new EditText(getContext());
        LayoutParams params = new LayoutParams(width, LayoutParams.WRAP_CONTENT);
        editText.setLayoutParams(params);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
            editText.setBackground(null);
        } else {
            editText.setBackgroundDrawable(null);
        }
        editText.setGravity(Gravity.CENTER_HORIZONTAL);
        editText.setTextColor(getContext().getResources().getColor(R.color.text_black));
        editText.setHint("-");
        editText.setHintTextColor(getContext().getResources().getColor(R.color.dialog_bg));
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        editText.setFocusable(false);
        editText.setFocusableInTouchMode(false);
        editText.setPadding(padding, padding, padding, padding);

        try {
            Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
            field.setAccessible(true);
            field.set(editText, R.drawable.edittext_cursor_drawable);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return editText;
    }

    private TextView getBlackPoint() {
        TextView textView = new TextView(getContext());
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        textView.setLayoutParams(params);
        textView.setTextColor(getContext().getResources().getColor(R.color.text_black));
        textView.setText(".");
        return textView;
    }

    private int mCurrentIndex = 0;

    private void initListener() {

        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = s.toString().trim();

                if (TextUtils.isEmpty(content)) {
                    return;
                }
                if (content.length() < 3) {
                    return;
                }

                int num = Integer.parseInt(content);
                if (num < 0 || num > 255) {
                    AppUtil.showShortToast(getContext().getApplicationContext(), "数字应该为0-255之间");
                    return;
                }
                nextEditView();
            }
        };

        OnFocusChangeListener changeListener = new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (v == mEditViewArray[0]) {
                        mCurrentIndex = 0;
                    } else if (v == mEditViewArray[1]) {
                        mCurrentIndex = 1;
                    } else if (v == mEditViewArray[2]) {
                        mCurrentIndex = 2;
                    } else {
                        mCurrentIndex = 3;
                    }
                }
            }
        };

        InputFilter[] lengthFilter = new InputFilter[]{new InputFilter.LengthFilter(3)};
        int len = mEditViewArray.length;
        for (int i = 0; i < len; i++) {
            mEditViewArray[i].setFilters(lengthFilter);
            mEditViewArray[i].addTextChangedListener(textWatcher);
            mEditViewArray[i].setOnFocusChangeListener(changeListener);
        }
    }

    public View getFirstView() {
        return mEditViewArray[0];
    }

    public void setContentText(String ip) {
        if (TextUtils.isEmpty(ip)) {
            return;
        }
        EditText[] view = mEditViewArray;

        String[] ipArr = ip.split("\\.");
        for (int i = 0; i < ipArr.length; i++) {
            view[i].setText(ipArr[i]);
        }

        requestFocusAndMoveCursor(view[3]);
    }

    /**
     * 获取ip内容。
     *
     * @return 字符串。
     */
    public String getContentIP() {
        StringBuilder builder = new StringBuilder();
        EditText[] view = mEditViewArray;
        String temp;
        for (int i = 0; i < view.length; i++) {
            temp = view[i].getText().toString().trim();
            if (TextUtils.isEmpty(temp)) {
                return "";
            }
            builder.append(temp);
            if (i != 3) {
                builder.append(".");
            }
        }
        return builder.toString();
    }

    protected void nextEditView() {

        if (mCurrentIndex == 3) {
            return;
        }

        mEditViewArray[++mCurrentIndex].requestFocus();
        int selection = mEditViewArray[mCurrentIndex].getText().length();
        JLog.d(TAG, "nextEditView:" + selection);
        mEditViewArray[mCurrentIndex].setSelection(selection);
    }

    protected void backToLastView(EditText[] editTexts) {
        if (mCurrentIndex == 0) {
            return;
        }
        EditText editText = editTexts[--mCurrentIndex];
        requestFocusAndMoveCursor(editText);
    }

    protected void requestFocusAndMoveCursor(EditText edit) {
        edit.requestFocus();
        edit.setSelection(edit.getText().toString().trim().length());
    }

    public void destroy() {
        if (mEditViewArray != null) {
            for (int i = 0; i < mEditViewArray.length; i++) {
                mEditViewArray[i] = null;
            }
            mEditViewArray = null;
        }
    }
}
